/**
 * Copyright (c) 2016-2020 https://github.com/zhaohuatai
 *
 * contact z_huatai@qq.com
 *  
 */
package org.zfes.snowy.common.variable.repository;

import java.util.Map;

import org.zfes.snowy.common.nosql.redis.jedis.SnowyJedisManager;
import org.zfes.snowy.core.exceptions.AppRuntimeException;
import org.zfes.snowy.core.util.ZStrUtil;

public class RedisVariableRepository extends AbstractVariableRepository {
	
	private static final String redisVariableHashKeyPrefix = "snowy_vars-";

    private SnowyJedisManager jedisManager;
    
    @Override
	protected Map<String, Object> doGetVariable(String varibaleName) {
    	if(!ZStrUtil.hasText(varibaleName)){
			throw new AppRuntimeException("varibaleName can not be null or empty ");
		}
		try {
			Map<String, Object> variable= (Map<String, Object>) getJedisManager().hashForObjGetAll(addPrefix(varibaleName));
			return variable;
		} catch (Exception e) {
	        throw new AppRuntimeException(e);
	    }
	}
	@Override
	protected void doPutVariable(String varibaleName, Map<String, Object> variable) {
		if(!ZStrUtil.hasText(varibaleName)){
			throw new AppRuntimeException("varibaleName can not be null or empty ");
		}
		if(variable==null||variable.isEmpty()){
			throw new AppRuntimeException("variable can not be null or empty ");
		}
        try {
        	getJedisManager().hashForObjSetAll(addPrefix(varibaleName), variable, 0);
        } catch (Exception e) {
        	throw new AppRuntimeException(e);
        }
	}

	@Override
	protected void doRemoveVariable(String varibaleName) {
		if(!ZStrUtil.hasText(varibaleName)){
			throw new AppRuntimeException("varibaleName can not be null or empty ");
		}
		  try {
			  getJedisManager().delBinary(addPrefix(varibaleName));
	        } catch (Exception e) {
	        	throw new AppRuntimeException(e);
	        }
	}


    public SnowyJedisManager getJedisManager() {
        return jedisManager;
    }

    public void setJedisManager(SnowyJedisManager jedisManager) {
        this.jedisManager = jedisManager;
    }

    private String addPrefix(String key) {
        return redisVariableHashKeyPrefix+ key;
    }
}
